package bigoo.common.communication.tcp;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class SocketWrapperManager {

    private Map<String, SocketWrapper> socketsMap = new HashMap<String, SocketWrapper>();

    public boolean containsSocket(String peerID) {
	return this.socketsMap.containsKey(peerID);

    }

    public void registerSocketWrapper(String peerID, SocketWrapper sockWrapper) {
	if (!this.containsSocket(peerID)) {
	    this.socketsMap.put(peerID, sockWrapper);

	    if (!sockWrapper.isAlive()) {
		sockWrapper.start();
	    }
	}

    }

    public void closeSocketWrapper(String peerID) throws IOException {
	SocketWrapper rem = this.socketsMap.remove(peerID);
	if (rem != null) {
	    rem.closeSocket();
	}
    }

    public SocketWrapper getSocketWrapper(String peerID) {
	return this.socketsMap.get(peerID);
    }

    public String findPeerID(SocketWrapper socketWrapper) {
	if (this.socketsMap.containsValue(socketWrapper)) {
	    String key = null;
	    for (Map.Entry<String, SocketWrapper> entry : this.socketsMap.entrySet()) {
		if (entry.getValue().equals(socketWrapper)) {
		    key = entry.getKey();
		    break;
		}
	    }
	    return key;
	} else {
	    return null;
	}

    }
}
